package net.hashcoding.cookbook.core;

import net.hashcoding.cookbook.core.controller.Controller;
import net.hashcoding.cookbook.core.controller.ControllerFactory;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

// TODO: more better router implement
public class Router {

    private static volatile Router router = null;

    public static Router getInstance() {
        if (router == null) {
            synchronized (Router.class) {
                if (router == null) {
                    router = new Router();
                }
            }
        }
        return router;
    }

    private HashMap<String, Controller> pathMap;

    private Router() {
        pathMap = new HashMap<>();
    }

    private void map(String path, Class<? extends Controller> clazz) {
        Controller controller = ControllerFactory.get(clazz);
        pathMap.put(path, controller);
    }

    private Controller parse(HttpServletRequest request) {
        String path = request.getRequestURI();
        if (pathMap.containsKey(path))
            return pathMap.get(path);
        return null;
    }

    public static void route(String path, Class<? extends Controller> clazz) {
        Router r = getInstance();
        r.map(path, clazz);
    }

    public static Controller redirect(HttpServletRequest request) {
        return getInstance().parse(request);
    }

}